package com.hugoo.file.slt;

import com.hugoo.core.Conf;
import com.hugoo.core.db.HSF;
import com.hugoo.core.db.mo.Record;
import com.hugoo.core.db.mo.RecordSet;
import com.hugoo.core.slt.AcFwd;
import com.hugoo.core.slt.Action;
import com.hugoo.core.util.TL;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.SocketException;
import java.net.URL;
import java.net.URLConnection;
import java.util.UUID;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.commons.net.util.Base64;

/**
 *
 * @author lovelock.chan
 */
public class FileAction extends Action {

    @Override
    public AcFwd exec(HttpServletRequest request, HttpServletResponse response) {
        if (this.checkPara(request, response)) {
            RecordSet<Record> rs = HSF.query("", "select * from meta_file_upload where scod='" + _sid + "'");
            File tmp = null;
            if (rs.next()) {
                Record rcd = rs.getRecord();
                File file = new File(rcd.getString("path"));
                if (file.exists()) {
                    try {
                        tmp = File.createTempFile(_sid, ".tmp");
                        if (file.exists()) {
                            log.info("本地系统中找到对应的下载文件...");
                            TL.copyFile(file, tmp);
                        }
                        this.writeDataToClient(request, response, tmp, rcd.getString("oname"));

                    } catch (IOException ex) {
                        this.writeDataToClient(response, "读取文件出错!");
                    }
                    return null;
                }
            }
            String rx = request.getParameter("EX__CCDD");
            if ("EME".equals(rx)) {
                log.info("所有的关联库无法找到相应资源，出现链式循环请求，现终止请求模式！");
                this.writeDataToClient(response, "所有的关联库无法找到相应资源，详联系管理员!");
                return null;
            }
            //本地未找到相关的请求文档的情况下，请求关联仓库
            String rex = Conf.getBaseProp("Rex.File.Resp");
            if (TL.isNotEmpty(rex)) {
                String uri = rex + request.getServletPath() + "?" + "&EX__CCDD=EME&__usid__=216C3F6028EA542D38D5433C636852B8&" + request.getQueryString();
                log.info("本地系统未找到对应的下载数据，现请求关联系统[" + uri + "]，加载下载文件数据。");
                try {
                    URL url = new URL(uri);

                    URLConnection conn = url.openConnection();
                    String xc = conn.getHeaderField("Content-Disposition");
                    {
                        response.setContentType("application/OCTET-STREAM");
                        String Agent = request.getHeader("User-Agent");
                        if (Agent.contains("MSIE")) {
                            //filename="=?UTF-8?B?TGlnaHRob3VzZS5qcGc=?="
                            String name;
                            if (xc.indexOf("=?UTF-8?B?") > 0) {
                                name = xc.substring(xc.indexOf("=?UTF-8?B?") + 10, xc.lastIndexOf("?="));
                                name = new String(Base64.decodeBase64(name));
                                log.info("远端取得文件【" + name + "】");
                                name = new String(name.getBytes("GBK"), "ISO-8859-1");
                            } else {
                                name = UUID.randomUUID().toString();
                            }
                            response.setHeader("Content-Disposition", "attachment; filename=\"" + name + "\"");
                        } else {
                            response.setHeader("Content-Disposition", conn.getHeaderField("Content-Disposition"));
                        }
                        response.addHeader("Content-Length", conn.getHeaderField("Content-Length"));
                    }
                    OutputStream os = null;
                    InputStream is = conn.getInputStream();
                    try {
                        os = response.getOutputStream();
                        byte[] b = new byte[4096];
                        int i;
                        while ((i = is.read(b)) > 0) {
                            os.write(b, 0, i);
                        }
                        os.flush();
                    } catch (SocketException e) {
                        log.info("客户端取消数据的接收！");
                    } catch (Exception e) {
                        log.warn("写出文件至客户端时出现异常[" + e.getMessage() + "]！");
                    } finally {
                        TL.close(os, is);
                    }
                    return null;
                } catch (Exception e) {
                    log.info("关联系统下载文件出现异常！", e);
                }
            }
        }
        this.writeDataToClient(response, "系统未找到[" + _sid + "]文件，请联系管理员！");
        return null;
    }
}
